#include "Base.h"
#include "Add.h"

VOID Add(BIGVALUE num1, BIGVALUE num2, BIGVALUE* pbvResult)
{
    BIGVALUE bvTemp ={0};
    BOOLEAN bAddOne = FALSE;
    BYTE* pucNum1 = NULL;
    BYTE* pucNum2 = NULL;
    BYTE* pucMax = NULL;
    BYTE* pucResult = NULL;
    ULONG ulMinBytes = (num1.ulByteCount < num2.ulByteCount) ? num1.ulByteCount : num2.ulByteCount;
    ULONG ulMaxBytes = (num1.ulByteCount > num2.ulByteCount) ? num1.ulByteCount : num2.ulByteCount;
    ULONG ulLoop = 0;
    ULONG ulTemp = 0;

    NewBigValue(&bvTemp, ulMaxBytes + 1);

    for(ulLoop = 0; ulLoop < ulMinBytes; ulTemp = 0, ulLoop++)
    {
        pucNum1 = num1.pucBuff + ulLoop;
        pucNum2 = num2.pucBuff + ulLoop;
        pucResult = bvTemp.pucBuff + ulLoop;
        ulTemp = *pucNum1 + *pucNum2;
        ulTemp += bAddOne;
        *pucResult = (BYTE)(ulTemp & 0xFF);
        bAddOne = (0 != (ulTemp & 0x100));
    }

    pucMax = (num1.ulByteCount > num2.ulByteCount) ? num1.pucBuff : num2.pucBuff;

    for(;ulLoop<ulMaxBytes; ulTemp = 0, ulLoop++)
    {
        pucNum1 =pucMax + ulLoop;
        pucResult = bvTemp.pucBuff + ulLoop;
        ulTemp = *pucNum1;
        ulTemp += bAddOne;
        *pucResult = (BYTE)(ulTemp & 0xFF);
        bAddOne = (0 != (ulTemp & 0x100));
    }

    if(bAddOne)
    {
        pucResult = bvTemp.pucBuff + (bvTemp.ulByteCount - 1);
        *pucResult = 1;
    }
    else
    {
        bvTemp.ulByteCount--;
    }

    CopyBigValue(bvTemp, pbvResult);
}


